<template>
  <div class="cart">
    <h4>全部商品</h4>
    <div class="cart-main">
      <div class="cart-th">
        <div class="cart-th1">全部</div>
        <div class="cart-th2">商品</div>
        <div class="cart-th3">单价（元）</div>
        <div class="cart-th4">数量</div>
        <div class="cart-th5">小计（元）</div>
        <div class="cart-th6">操作</div>
      </div>
      <div class="cart-body">
        <ul class="cart-list" v-for="cartInfo in cartInfoList" :key="cartInfo.id">
          <li class="cart-list-con1">
            <input type="checkbox" name="chk_list" :checked="!!cartInfo.isChecked"
              @change="checkCartInfoState(cartInfo)" />
          </li>
          <li class="cart-list-con2">
            <img :src="cartInfo.imgUrl" />
            <div class="item-msg">
              {{ cartInfo.skuName }}
            </div>
          </li>
          <li class="cart-list-con4">
            <span class="price">{{ cartInfo.skuPrice }}</span>
          </li>
          <li class="cart-list-con5">
            <a href="javascript:void(0)" class="mins" @click="changeSkuNum('decrement', cartInfo)">-</a>
            <input autocomplete="off" type="text" :value="cartInfo.skuNum" minnum="1"
              @change="changeSkuNum('change', cartInfo, $event)" class="itxt" />
            <a href="javascript:void(0)" class="plus" @click="changeSkuNum('increment', cartInfo)">+</a>
          </li>
          <li class="cart-list-con6">
            <span class="sum">{{ cartInfo.skuPrice * cartInfo.skuNum }}</span>
          </li>
          <li class="cart-list-con7">
            <a href="javascript:;" class="sindelet" @click="showDialogByDelOneCartInfo(cartInfo.skuId)""
              >删除</a
            >
            <br />
            <a href=" #none">移到收藏</a>
          </li>
        </ul>
      </div>
    </div>
    <div class="cart-tool">
      <div class="select-all">
        <input class="chooseAll" type="checkbox" v-model="checkAll" />
        <span>全选</span>
      </div>
      <div class="option">
        <a href="javascript:;" @click="showDialogByDelSelected">删除选中的商品</a>
        <a href="#none">移到我的关注</a>
        <a href="#none">清除下柜商品</a>
      </div>
      <div class="money-box">
        <div class="chosed">已选择 <span>{{ selectedCount }}</span>件商品</div>
        <div class="sumprice">
          <em>总价（不含运费） ：</em>
          <i class="summoney">{{ selectedMoney }}</i>
        </div>
        <div class="sumbtn">
          <router-link class="sum-btn" to="/trade" >结算</router-link>
        </div>
      </div>
    </div>
    <Dialog :visible.sync="visible">
      <template v-slot:header>
        <p>提示</p>
      </template>
      <template>
        <p>您真的确定要删除{{ isDelOne ? "这条" : "这些选中的" }}商品吗？</p>
      </template>
      <template #footer>
        <div class="btn-footer">
          <button class="btn" @click="visible = false">取消</button>
          <button class="btn primary" @click="delShopCartInfo">确认</button>
        </div>
      </template>
    </Dialog>
  </div>
</template>

<script>
import {
  reqShopCartListData,
  reqChangeShopCartInfoState,
  reqDelOnShopCartInfo,
  reqDelSelectedCartInfo,
  reqAddOrUpdateCart,
} from "@/api";
import { skuNumReg } from "@/utils/reg"
export default {
  name: "ShopCart",
  data() {
    return {
      cartInfoList: [], // 当前购物车中要渲染的总数据
      visible: false, // 默认值
      skuId: "", // 商品的id
      isDelOne: false, // 是否删除一条
      skuIdList: [], // 待删除商品的id
      leftCartInfoList: [], // 剩余未删除的商品
    };
  },
  // 1. 获取购物车数据 并渲染到页面当中
  async mounted() {
    const result = await reqShopCartListData();
    // console.log("shopcart", result);
    if (result.code === 200) {
      this.cartInfoList = result.data.length ? result.data[0].cartInfoList : [];
    } else {
      console.log(result.message);
    }
  },
  methods: {
    // 2. 修改购物车中商品的选中状态
    async checkCartInfoState(cartInfo) {
      let isChecked = 1 - cartInfo.isChecked;
      const result = await reqChangeShopCartInfoState(
        cartInfo.skuId,
        isChecked
      );
      if (result.code === 200) {
        // 更新服务器数据成功后，重新更新页面
        cartInfo.isChecked = isChecked;
      } else {
        console.log(result.message);
      }
    },
    //2、删除一个商品时的弹出框
    showDialogByDelOneCartInfo(skuId) {
      this.skuId = skuId; //收集待删除商品的id
      this.visible = true; // 弹出对话框
      this.isDelOne = true; // 是删除一条商品吗
    },
    // 3. 单击弹出框的确定按钮 删除一条商品数据或实现批量删除
    async delShopCartInfo() {
      if (this.isDelOne) {
        // 删除一条商品
        const result = await reqDelOnShopCartInfo(this.skuId);
        if (result.code === 200) {
          this.visible = false; // 隐藏对话框
          // 正常情况下，当删除购物车中的商品数据成功的时候，需要做两件事
          // 1. 隐藏弹出来的对话框 2. 页面应该要显示剩下的商品数(刷新 一般要重新刷新页面重发请求)
          this.cartInfoList = this.cartInfoList.filter(
            (cartInfo) => cartInfo.skuId !== this.skuId
          );
          this.isShow = false;
        } else {
          alert("删除本条商品数据失败！！");
        }
        return; // 不要再往下执行了
      }

      const result = await reqDelSelectedCartInfo(this.skuIdList);
      console.log("delSelected", result);
      if (result.code === 200) {
        this.visible = false; // 关闭对话框
        this.cartInfoList = this.leftCartInfoList.filter(
          (item) => item.isChecked === 0
        );
      } else {
        console.log(result.message);
      }
    },
    //4、单击批量删除按钮时弹出对话框
    showDialogByDelSelected() {
      // 4.0 清空数组
      this.skuIdList = [];
      //删除一条还是多条商品
      this.isDelOne = false;
      this.leftCartInfoList = [];
      // 4.1 弹出对话框
      this.visible = true;

      // 4.2 收集被选中的商品的id
      this.cartInfoList.forEach((cartInfo) => {
        if (cartInfo.isChecked === 1) {
          this.skuIdList.push(cartInfo.skuId);
        } else {
          this.leftCartInfoList.push(cartInfo);
        }
      });

      // 4.3 区分批量删除
      this.isDelOne = false;
    },
    // 更新商品数量
    async changeSkuNum(type, cartInfo, e) {
      let num = 0;
      switch (type) {
        case "increment":
          if (cartInfo.skuNum < 200) {
            cartInfo.skuNum++;
            num++;
          } // 这是发给服务器的数量
          break;
        case "decrement":
          num--;
          cartInfo.skuNum--;
          if (cartInfo.skuNum < 1) {
            cartInfo.skuNum = 1;
            num = 0
          }
          break;
        case "change":
          let newSkuNum = e.target.value; // 获取用户输入的值
          let oldSkuNum = cartInfo.skuNum //旧值
          if (skuNumReg.test(newSkuNum)) {
            cartInfo.skuNum = newSkuNum; // 重新赋值 让页面看起来是重新输入的值
            num = newSkuNum - oldSkuNum; // 用当前输入的值减去之前值
            if (newSkuNum > 200) {
              cartInfo.skuNum = 200
              num = 200 - oldSkuNum
            }
          } else {
            // cartInfo.skuNum = 1;
            e.target.value = oldSkuNum
          }
          break;
      }
      if (num === 0) return
      //统一发送ajax请求
      const result = await reqAddOrUpdateCart(cartInfo.skuId, num);
      if (result.code === 200) {
        console.log('更改数据成功...');
      } else {
        console.log('更改数据失败...');
      }
    },
  },
  computed: {
    // 1. 实现全选 全不选
    checkAll: {
      get() {
        // 访问复选框就会执行这个里面的代码
        // console.log('我被执行了...');
        // 一开始渲染当前购物车组件的时候，应该让全选按钮有一个状态 是不是选中的状态
        // 这个全选按钮是否选中，取决于所有的小按钮状态，只有当所有的小按钮都被选中的，总的这个全选按钮才被选中
        // 如果有一个小按钮不被选中，则这个总按钮也不要被选中
        // every 强调是一个整体 总所有的都满足条件 最终结果 才是true 有一个不满足就是false
        return this.cartInfoList.every((cartInfo) => cartInfo.isChecked === 1);
      },
      set(val) {
        // 只要一更改，就会执行这里面的代码
        this.cartInfoList.forEach((cartInfo) => {
          let isChecked = val ? 1 : 0;
          cartInfo.isChecked = isChecked;

          // 去发送请求，一条条的进行更新
          this.checkCartInfoState({
            skuId: cartInfo.skuId,
            isChecked: 1 - isChecked,
          });
        });
      },
    },
    // 2、已选商品个数
    selectedCount() {
      return this.cartInfoList.reduce(
        (prev, current) => prev + current.isChecked,
        0
      );
    },
    //3、统计总金额
    selectedMoney() {
      return this.cartInfoList.reduce(
        (prev, current) =>
          prev + current.isChecked * current.skuPrice * current.skuNum,
        0
      );
    },
  },
  watch: {
    visible: {
      immediate: true, // 一开始立即就监视
      handler() {
        if (this.visible) {
          document.documentElement.style.overflow = "hidden";
        } else {
          document.documentElement.style.overflow = "auto";
        }
      },
    },
  },

}
</script>

<style lang="less" scoped>
.cart {
  width: 1200px;
  margin: 0 auto;

  h4 {
    margin: 9px 0;
    font-size: 14px;
    line-height: 21px;
  }

  .cart-main {
    .cart-th {
      background: #f5f5f5;
      border: 1px solid #ddd;
      padding: 10px;
      overflow: hidden;

      &>div {
        float: left;
      }

      .cart-th1 {
        width: 25%;

        input {
          vertical-align: middle;
        }

        span {
          vertical-align: middle;
        }
      }

      .cart-th2 {
        width: 25%;
      }

      .cart-th3,
      .cart-th4,
      .cart-th5,
      .cart-th6 {
        width: 12.5%;
      }
    }

    .cart-body {
      margin: 15px 0;
      border: 1px solid #ddd;

      .cart-list {
        padding: 10px;
        border-bottom: 1px solid #ddd;
        overflow: hidden;

        &>li {
          float: left;
        }

        .cart-list-con1 {
          width: 15%;
        }

        .cart-list-con2 {
          width: 35%;

          img {
            width: 82px;
            height: 82px;
            float: left;
          }

          .item-msg {
            float: left;
            width: 150px;
            margin: 0 10px;
            line-height: 18px;
          }
        }

        .cart-list-con4 {
          width: 10%;
        }

        .cart-list-con5 {
          width: 17%;

          .mins {
            border: 1px solid #ddd;
            border-right: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
          }

          input {
            border: 1px solid #ddd;
            width: 40px;
            height: 33px;
            float: left;
            text-align: center;
            font-size: 14px;
          }

          .plus {
            border: 1px solid #ddd;
            border-left: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
          }
        }

        .cart-list-con6 {
          width: 10%;

          .sum {
            font-size: 16px;
          }
        }

        .cart-list-con7 {
          width: 13%;

          a {
            color: #666;
          }
        }
      }
    }
  }

  .cart-tool {
    overflow: hidden;
    border: 1px solid #ddd;

    .select-all {
      padding: 10px;
      overflow: hidden;
      float: left;

      span {
        vertical-align: middle;
      }

      input {
        vertical-align: middle;
      }
    }

    .option {
      padding: 10px;
      overflow: hidden;
      float: left;

      a {
        float: left;
        padding: 0 10px;
        color: #666;
      }
    }

    .money-box {
      float: right;

      .chosed {
        line-height: 26px;
        float: left;
        padding: 0 10px;
      }

      .sumprice {
        width: 200px;
        line-height: 22px;
        float: left;
        padding: 0 10px;

        .summoney {
          color: #c81623;
          font-size: 16px;
        }
      }

      .sumbtn {
        float: right;

        a {
          display: block;
          position: relative;
          width: 96px;
          height: 52px;
          line-height: 52px;
          color: #fff;
          text-align: center;
          font-size: 18px;
          font-family: "Microsoft YaHei";
          background: #e1251b;
          overflow: hidden;
        }
      }
    }
  }

  .btn-footer {
    position: absolute;
    right: 40px;
    bottom: 20px;

    .btn {
      width: 62px;
      height: 32px;
      font-size: 14px;
      margin-left: 16px;
      border-width: 1px;
      border-radius: 10%;
      cursor: pointer;

      &.primary {
        background-color: rgb(102, 177, 255);
        color: #fff;
      }
    }
  }
}
</style>
